package com.example.cash_register.service;


import com.example.cash_register.mapper.UserMapper;
import com.example.cash_register.model.user.User;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserService {
    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public User register(String username,String password) {
        String salt = BCrypt.gensalt();
        String hashPassword = BCrypt.hashpw(password,salt);

        User user = new User(username,hashPassword);
        userMapper.insert(user);
        return user;
    }

    public User login(String username,String password) {
        User user = userMapper.selectByUsername(username);

        log.debug("通过 mybatis 查询得到的用户 = {}",user);

        if (user == null) {
            return null;
        }
        if (!BCrypt.checkpw(password,user.getPassword())) {
            return null;
        }
        return user;
    }
}
